<?php

function connect()
{
    require 'application/config.php';
    if (!class_exists('PDO', false))
    {
        echo "PHP PDO package is required.";
        exit(0);
    }

    if (empty($config))
    {
        echo "Database definitions required.";
        exit(0);
    }

    $dsn = !empty($config['dsn']) ? $config['dsn'] : "{$config['type']}:host={$config['host']};dbname={$config['name']};charset={$config['charset']}";

    try
    {
        $pdo = new PDO(
                        $dsn,
                        $config['user'],
                        $config['pass'],
                        array(PDO::ATTR_PERSISTENT => !empty($config['persistent']) ? true : false)
        );
        $pdo->exec("SET CHARACTER SET {$config['charset']}");
    }
    catch (PDOException $e)
    {
        throw new Exception(sprintf("Can't connect to PDO database '{$config['type']}'. Error: %s", $e->getMessage()));
    }

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $pdo;
}

function content($name, $page, $length = NULL)
{
    $pdo = connect();
    $query = $pdo->prepare("SELECT COUNT(*) FROM cms_blocks WHERE name_block = ? and page_block = ?");
    $query->execute(array($name, $page));
    if ($query->fetchColumn() > 0)
    {
        $query = $pdo->prepare("SELECT * FROM cms_blocks WHERE name_block = ? and page_block = ?");
        $query->execute(array($name, $page));
        $block = $query->fetch(PDO::FETCH_ASSOC);
        echo $block['content_block'];
    }
    else
    {
        $date = date("Y-m-d");
        $query = $pdo->prepare("INSERT INTO cms_blocks (name_block, page_block, length_block, date_block) VALUES (?, ?, ?, ?)");
        $query->execute(array($name, $page, $length, $date));
    }
    $query = null;
    $pdo = null;
}

